package com.file;

import org.junit.Test;

import java.io.File;
import java.io.IOException;

/**
 * @Author WaveHi
 * @Date 20/8/2021 上午 9:46
 * @Version 1.0
 * @Contact HJBWaveHi@163.com
 * @Description Test the use  of class java.io.File
 */
public class TestFile {

    public static void main(String[] args) {

        //获取需删除的文件
        File file = new File("day11/txtTest/txt");

        //测试
        TestFile testFile = new TestFile();
        testFile.deleteDirectory(file);


    }

    @Test
    public void useFile() {

        File dir1 = new File("txt1");
        File file1 = new File("txt/hello.txt");
        File file2 = new File("txt1/hello.txt");

        //判断上层目录是否存在
        File parent = new File(file2.getParent());
        try {
            if(parent.exists()) {

                //创建
                file2.createNewFile();

            }else {

                parent.mkdirs();
                file2.createNewFile();

            }
        } catch (IOException e) {
            e.printStackTrace();
        }


    }

    @Test
    public void testDelete() {

        //获取需删除的文件
        File dir1 = new File("txtTest/txt");

        //删除
        deleteDirectory(dir1);

    }

    /*
    删除文件夹 如果文件夹有文件则删除文件，有文件夹需要进一不判断里面是否有内容，有则进一步删除
     */

    /**
     * 删除文件或文件夹
     * @param file 需要删除的文件
     */
    @Test
    public void deleteDirectory(File file) {

        //标记方法是否执行成功
        boolean isCompleted = false;

        //异常情况处理
        if(!file.exists()){

            throw new RuntimeException("File do not exist.");

        }
        if(file.isDirectory()) {

            File[] files = file.listFiles();
            for(int i = 0;i < files.length;i++) {

                deleteDirectory(files[i]);

            }

        }

        isCompleted = file.delete();


        if(!isCompleted) {

            throw new RuntimeException("File delete failed.");

        }


    }

    public long length(File file) {


        //异常情况处理
        if(file == null || !file.exists()) {

            throw new RuntimeException("The argument is illegal");

        }

        long sum = 0;

        //判断文件类型
        if(file.isDirectory()) {

            File[] files = file.listFiles();

            for(int i = 0;i < files.length;i++) {

                sum += length(files[i]);

            }

        }else {

            sum += file.length();

        }

        return sum;

    }

}
